/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package main

import (
	"embed"
	"flag"
	"fmt"
	"gitee.com/bigmouth/quick-mock/src/domain/service"
	"gitee.com/bigmouth/quick-mock/src/infrastructure/config"
	"gitee.com/bigmouth/quick-mock/src/infrastructure/log"
	"gitee.com/bigmouth/quick-mock/src/infrastructure/server"
	"gitee.com/bigmouth/quick-mock/src/presentation/base"
	"gitee.com/bigmouth/quick-mock/src/presentation/mock"
	"gitee.com/bigmouth/quick-mock/src/presentation/namespace"
	"gitee.com/bigmouth/quick-mock/src/presentation/web"
	"github.com/robfig/cron/v3"
	"html/template"
)

var (
	port       = flag.Int("port", 9999, "run at port")
	extTraceId = flag.String("ext-trace-id", "", "extends support traceIds, used comma split")
)

//go:embed assets
var assetsF embed.FS

func main() {
	flag.Parse()
	s := server.Default()
	tmpl := template.Must(template.New("").ParseFS(assetsF, "assets/templates/*.html"))
	s.Engine.SetHTMLTemplate(tmpl)
	// 加载配置
	config.New(*extTraceId)
	// 加载模块路由
	loadRoute(s)
	c := cron.New()
	loadCron(c)
	if err := s.Run(fmt.Sprintf(":%d", *port)); err != nil {
		panic(fmt.Errorf("start err:%w", err))
	}
}

func loadRoute(s *server.Server) {
	// 基础功能
	base.LoadRoute(s)
	// namespace
	namespace.LoadRoute(s)
	// mock api
	mock.LoadRoute(s)
	// web页面
	web.LoadRoute(s)
}

func loadCron(c *cron.Cron) {
	_, err := c.AddFunc("@every 1h", func() {
		service.GetNamespaceInstance().CleanTimeout()
	})
	if err != nil {
		log.Error("start cron error:%s", err)
		return
	}
	c.Start()
	log.Info("cron start!")
}
